import re

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.base_user import BaseUserManager

from apps.users.models import Users_model
from django.db.models import Q


def authenticate(self, request, username=None, password=None, **kwargs):
    if username is None:
        username = kwargs.get(Users_model.USERNAME_FIELD)
    try:
        user = Users_model._default_manager.get_by_natural_key(username)
    except Users_model.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        Users_model().set_password(password)
    else:
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

#邮箱和用户名都可以登录
# 基础ModelBackend类，因为它有authenticate方法
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 1.　todo 不管是用户或者邮箱或者手机号码，第一件事获取对象
        try:
            # todo 先通过正则，判断出手机号码/用户名/邮箱
            if re.match(r'^1[\d]{10}$', username):
                user = Users_model.objects.get(user_mobile=username)
            elif re.match('^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$', username):
                user = Users_model.objects.get(email=username)
            else:
                user = Users_model.objects.get(user_code=username)

        except Users_model.DoesNotExist:
            user = None

            # todo 拿到user之后进行校验
        if user is not None and user.check_password(password):
            return user
